package com.zengge.zbc.interceptor;

import com.zengge.zbc.dto.Certificate;
import com.zengge.zbc.utils.JsonUtils;
import com.zengge.zbc.utils.SecretUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Tate implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){


        String token = request.getHeader("tate");

        try {
            String json = SecretUtils.decrypt(token);
            Certificate certificate = JsonUtils.toObject(json,Certificate.class);
            if(certificate == null){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            request.setAttribute("userId",Long.parseLong(certificate.getUserId()));
            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }
}
